package com.zecan.blog.controller;

import com.zecan.blog.common.BlogResult;
import com.zecan.blog.common.status.UserStatus;
import com.zecan.blog.controller.annotation.AccessLimit;
import com.zecan.blog.controller.exception.UserException;
import com.zecan.blog.dao.UserMapper;
import com.zecan.blog.dao.converter.BlogUserConverter;
import com.zecan.blog.dto.user.RegistryUserDto;
import com.zecan.blog.dto.user.UpdateUserInfoDto;
import com.zecan.blog.dto.atricle.UserArticleDto;
import com.zecan.blog.entity.BlogUser;
import com.zecan.blog.service.ArticleService;
import com.zecan.blog.service.BlogUserService;
import com.zecan.blog.utils.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @ClassName LoginController
 * @Description
 * @date 2022/10/29 12:21
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private BlogUserService userService;

    @Resource
    private ArticleService articleService;

    @Resource
    private UserMapper userMapper;
    /**
     * 用户注册
     *
     * @param registryUserDto 前端传递过来的form表单信息
     * @return json
     */
    @RequestMapping(value = "/registry", method = RequestMethod.POST)
    public BlogResult registryUser(RegistryUserDto registryUserDto) {
        // 检查用户信息
        userService.checkMsg(registryUserDto);
        userService.registryBlogUser(BlogUserConverter.INSTANCE.userRegConverterEntity(registryUserDto));
        return BlogResultUtils.userStatus(UserStatus.USER_REG_SUCCESS);
    }

    /**
     * 获取验证码
     * @param captchaKey
     * @throws IOException
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(String captchaKey) throws IOException {
        userService.getCaptchaImg(captchaKey);
    }


    /**
     * 发送邮箱
     *
     * @param email      邮箱
     * @param emailKey   邮箱code 由前端自动生成
     * @param isRegistry 是否是注册
     * @return code
     */
    @AccessLimit(seconds = 60,maxCount = 1)
    @RequestMapping(value = "/emailCaptcha", method = RequestMethod.GET)
    public BlogResult emailCaptcha(String email, String emailKey, Boolean isRegistry)  {

        // 校验==> 发送Code
        userService.sendEmailMsg(email, emailKey, isRegistry);
        // 响应前端
        return BlogResultUtils.userStatus(UserStatus.USER_SEND_EMAIL_SUCCESS);

    }

    /**
     * 用户个人中心修改用户头像的时候先进行上传
     * @param multipartFile 头像数据
     * @return json
     */
    @RequestMapping(value = "/update/avatar", method = RequestMethod.POST)
    public BlogResult addUserAvatar(@RequestParam("avatarImage") MultipartFile multipartFile) {
        String avatarUrl = userService.uploadUserAvatar(multipartFile);
        return BlogResultUtils.ok(avatarUrl,"上传成功");
    }


    /**
     * 更新用户信息
     * @param userInfoDto dto
     * @return
     */
    @AccessLimit(seconds = 5,maxCount = 1)
    @PreAuthorize("hasAuthority('user') OR hasAuthority('admin')" )
    @RequestMapping(value = "/update/userInfo", method = RequestMethod.POST)
    public BlogResult uploadUserInfo(UpdateUserInfoDto userInfoDto) {
        userService.updateUserInfo( BlogUserConverter.INSTANCE.userUpdateConverterEntity(userInfoDto));

        return BlogResultUtils.userStatus(UserStatus.USER_UPDATE_INFO_SUCCESS);
    }

    /**
     * 获取登录用户的文章信息
     * @param userArticleDto
     * @return
     */
    @PreAuthorize("hasAuthority('user') OR hasAuthority('admin')" )
    @RequestMapping(value = "/userArticle", method = RequestMethod.POST)
    public BlogResult getUserArticle(UserArticleDto userArticleDto){
      return BlogResultUtils.userStatus(  articleService.getArticleListByUserId(userArticleDto),UserStatus.USER_GET_ARTICLE_SUCCESS);
    }

    /**
     * 获取用户文章内容
     * @param articleId
     * @return
     */
    @PreAuthorize("hasAuthority('user') OR hasAuthority('admin')" )
    @RequestMapping(value = "/userArticleContent", method = RequestMethod.GET)
    public BlogResult getUserArticleContent(Integer articleId) {
        return BlogResultUtils.userStatus(articleService.getUserArticleContent(articleId),UserStatus.USER_GET_ARTICLE_SUCCESS);
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @RequestMapping(
            value = {"/blogInfo"},
            method = {RequestMethod.GET}
    )
    public BlogResult getUserBlogData(Integer userId) {
        assert userId != null;

        return BlogResultUtils.userStatus(this.userService.getUserBlogInfo(userId), UserStatus.USER_GET_BLOG_MSG_SUCCESS);
    }


    /**
     * 获取用户列表
     * @param offset
     * @param limit
     * @return
     */
    @PreAuthorize("hasAuthority('admin')" )
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public BlogResult getUserList(Integer offset ,Integer limit) {
        return BlogResultUtils.ok(userService.getBgUserInfoList(offset, limit),"获取用户列表成功");
    }


    /**
     * 修改用户信息或新增用户信息
     * @param userInfoDto
     * @return
     */
    @PreAuthorize("hasAuthority('admin')" )
    @RequestMapping(value = "/bg_update", method = RequestMethod.POST)
    public BlogResult updateUserInfo(UpdateUserInfoDto userInfoDto) {
        if(userInfoDto.getIsUpdate()) {
            userService.updateBgUserInfo(userInfoDto);
            return BlogResultUtils.ok("修改用户信息成功");
        }else {
            BlogUser userByUsername = userMapper.findUserByUsername(userInfoDto.getUsername());
            // 当前用户名已注册
            if (userByUsername != null) {
                throw new UserException(UserStatus.USER_NAME_ALREADY_REG);
            }
            userService.registryBlogUser(BlogUserConverter.INSTANCE.bgUserUpdateConverterEntity(userInfoDto));
            return BlogResultUtils.ok("新增用户信息成功");
        }

    }

    @PreAuthorize("hasAuthority('admin')" )
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public BlogResult delUser( Integer userId) {
        userService.delUser(userId);
        return BlogResultUtils.ok("删除用户成功");
    }


    @PreAuthorize("hasAuthority('admin')" )
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public BlogResult resetUserPwd( Integer userId) {
        userService.resetUserPwd(userId);
        return BlogResultUtils.ok("重设密码成功");
    }

}
